package com.example.loginpage.InputUtil

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.IOException
import org.json.JSONObject

class AudioViewModel: ViewModel() {
    private val _accessToken = MutableLiveData<String>()
    val accessToken: LiveData<String> = _accessToken

    private val _myWords = MutableLiveData<String>()
    val myWords: LiveData<String> = _myWords
    fun clearMyWords(){
        _myWords.postValue("null")
    }
    fun getIAM(ak: String, sk: String) {
        var myToken: String = ""

        viewModelScope.launch(Dispatchers.IO) {
            val client = OkHttpClient()
            val requestUrl = "https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens"
            val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull()
            val body = "{\"auth\":{\"identity\":{\"methods\":[\"hw_ak_sk\"],\"hw_ak_sk\":{\"access\":{\"key\":\"$ak\"},\"secret\":{\"key\":\"$sk\"}}},\"scope\":{\"project\":{\"name\":\"cn-north-4\"}}}}"
                .toRequestBody(mediaType)

            val request = Request.Builder()
                .url(requestUrl)
                .post(body)
                .build()

            try {
                val response: Response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    myToken = response.header("X-Subject-Token").orEmpty()
                    withContext(Dispatchers.Main) {
                        // 更新UI或处理成功情况
                        _accessToken.postValue(myToken)
                    }
                } else {
                    throw IOException("Unexpected code $response")
                }
            } catch (e: IOException) {
                withContext(Dispatchers.Main) {
                    // 处理错误情况
                    e.printStackTrace()
                }
            }
        }
    }

    private suspend fun sendSISRequest(base64Data: String): String {
        val requestUrl = "https://sis-ext.cn-north-4.myhuaweicloud.com/v1/d8047c5a9ef04fe3bf7d842c0ab92951/asr/short-audio"
        val token = accessToken.value.toString()
        val mediaType = "application/json; charset=utf-8".toMediaTypeOrNull()
        val body = "{\"config\":{\"audio_format\":\"auto\",\"property\":\"chinese_16k_general\",\"add_punc\":\"yes\",\"need_word_info\":\"yes\"},\"data\":\"$base64Data\"}"
            .toRequestBody(mediaType)

        val request = Request.Builder()
            .url(requestUrl)
            .post(body)
            .addHeader("Content-Type", "application/json")
            .addHeader("X-Auth-Token", token)
            .build()

        return withContext(Dispatchers.IO) {
            try {
                val client = OkHttpClient()
                val response: Response = client.newCall(request).execute()
                if (response.isSuccessful) {
                    val responseBody = response.body?.string() ?: ""
                    val resultText = extractResultText(responseBody)
                    resultText
                } else {
                    throw IOException("Unexpected code $response")
                }
            } catch (e: IOException) {
                e.printStackTrace()
                throw e
            }
        }
    }
    fun performSISRequest(base64Data: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val result = sendSISRequest(base64Data)
                withContext(Dispatchers.Main) {
                    _myWords.postValue(result)
                }
            } catch (e: IOException) {
                withContext(Dispatchers.Main) {
                    // 处理错误情况，例如显示错误消息
                    e.printStackTrace()
                }
            }
        }
    }
    private fun extractResultText(jsonString: String): String {
        val json = JSONObject(jsonString)
        val result = json.getJSONObject("result")
        return result.getString("text")
    }
}